package com.fdb.efp.nls.service.impl;

import com.fdb.basic.framework.core.base.FrameworkService;
import com.fdb.basic.framework.core.util.MD5Util;
import com.fdb.basic.framework.core.util.StringUtil;
import com.fdb.basic.framework.core.util.TimeUtil;
import com.fdb.efp.nls.common.ConsoleConstant;
import com.fdb.efp.nls.service.dao.SUserDao;
import com.fdb.efp.nls.service.dao.SUserDutyDao;
import com.fdb.efp.nls.service.dao.SUserOrgDao;
import com.fdb.efp.nls.service.dao.SUserRoleDao;
import com.fdb.efp.nls.service.domain.SUser;
import com.fdb.efp.nls.service.domain.SUserDuty;
import com.fdb.efp.nls.service.domain.SUserOrg;
import com.fdb.efp.nls.service.domain.SUserRole;
import com.fdb.efp.nls.service.facade.SUserService;
import com.fdb.efp.nls.service.vo.SUserDutyVO;
import com.fdb.efp.nls.service.vo.SUserRoleVO;
import com.fdb.efp.nls.service.vo.SUserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>ServiceImpl: 系统用户表				<p>
 *
 * @author chenqm1
 * @date 2018-05-03
 */
@Service("sUserService")
public class SUserServiceImpl implements SUserService, FrameworkService {

    private static Logger logger = LoggerFactory.getLogger(SUserServiceImpl.class);

    @Autowired
    private SUserDao sUserDao;

    @Autowired
    private SUserDutyDao sUserDutyDao;

    @Autowired
    private SUserRoleDao sUserRoleDao;

    @Autowired
    private SUserOrgDao sUserOrgDao;

    @Override
	public int insertOrUpdateByPk(SUserVO inSUserVo) {
		logger.debug("当前修改数据为:" + inSUserVo.toString());
		int num = 0;
		try {
			SUser sUser = new SUser();
			beanCopy(inSUserVo, sUser);
			setInsertDefaultProperty(sUser);
            //sUser.setUserCode(sUser.getUserName());
            //sUser.setUserPwd(MD5Util.getMD5ofStr(sUser.getUserCode()+sUser.getUserCode()));
            sUser.setLegalOrgCode(inSUserVo.getLegalOrgCode());

            SUserOrg sUserOrg = new SUserOrg();
            sUserOrg.setUserCode(sUser.getUserCode());
            sUserOrg.setOrgCode(inSUserVo.getOrgCode());
            sUserOrg.setLegalOrgCode(inSUserVo.getLegalOrgCode());
            sUserOrg.setLastUpdateUser(inSUserVo.getLoginUserId());
            sUserOrg.setLastUpdateTime(TimeUtil.getCurrentDateTime());
            num = sUserDao.insertOrUpdateByPk(sUser);
            num += sUserOrgDao.insertSUserOrgOrUpdateByPk(sUserOrg);
		} catch (Exception e) {
			logger.error("修改数据发生异常!", e);
			num = -1;
		}
		logger.debug("根据条件:" + inSUserVo + "修改的数据条数为" + num);
		return num;
	}
    /**
     * 新增操作
     */
    public int insertSUser(SUserVO inSUserVo) {
        logger.debug("当前新增数据为:" + inSUserVo.toString());
        int num;
        try {
            SUser sUser = new SUser();
            beanCopy(inSUserVo, sUser);
            setInsertDefaultProperty(sUser);
            //sUser.setUserCode(sUser.getUserName());
            
            sUser.setUserPwd(MD5Util.getMD5ofStr(sUser.getUserCode()+sUser.getUserCode()));
            sUser.setLegalOrgCode(inSUserVo.getLegalOrgCode());
            SUserOrg sUserOrg = new SUserOrg();
            sUserOrg.setUserCode(sUser.getUserCode());
            sUserOrg.setOrgCode(inSUserVo.getOrgCode());
            sUserOrg.setLegalOrgCode(inSUserVo.getLegalOrgCode());
            sUserOrg.setLastUpdateUser(inSUserVo.getLoginUserId());
            sUserOrg.setLastUpdateTime(TimeUtil.getCurrentDateTime());
            num = sUserDao.insertSUser(sUser);
            num += sUserOrgDao.insertSUserOrg(sUserOrg);
        } catch (Exception e) {
            logger.error("新增数据发生异常!", e);
            num = -1;
        }
        logger.debug("当前新增数据条数为:" + num);
        return num;
    }

    /**
     * 删除操作
     */
    public int deleteByPk(SUserVO inSUserVo) {
        logger.debug("当前删除数据条件为:" + inSUserVo);
        int num;
        try {
            SUser sUser = new SUser();
            beanCopy(inSUserVo, sUser);
            SUser temp = sUserDao.queryByPk(sUser);
            //只有正常才能注销
            if (!StringUtil.isEmpty(temp.getStatus()) && ConsoleConstant.USER_STATUS_1.equals(temp.getStatus())) {
                num = sUserDao.deleteByPk(sUser);
                /*setUpdateDefaultProperty(inSUserVo);
                SUser sUser = new SUser();
                beanCopy(inSUserVo, sUser);
                num = sUserDao.deleteByPk(sUser);
                SUserOrg sUserOrg = new SUserOrg();
                sUserOrg.setUserCode(sUser.getUserCode());
                num += sUserOrgDao.deleteByPk(sUserOrg);
                SUserDuty sUserDuty = new SUserDuty();
                sUserDuty.setUserCode(sUser.getUserCode());
                num += sUserDutyDao.deleteByPk(sUserDuty);
                SUserRole sUserRole = new SUserRole();
                sUserRole.setUserCode(sUser.getUserCode());
                num += sUserRoleDao.deleteByPk(sUserRole);*/
            }
            else
                num = -1;
        } catch (Exception e) {
            logger.error("删除数据发生异常!", e);
            num = -1;
        }
        logger.debug("根据条件:" + inSUserVo + "删除的数据条数为" + num);
        return num;
    }


    /**
     * 更新操作
     */
    public int updateByPk(SUserVO inSUserVo) {
        logger.debug("当前修改数据为:" + inSUserVo.toString());
        int num = 0;
        try {
            SUser sUser = new SUser();
            beanCopy(inSUserVo, sUser);
            setUpdateDefaultProperty(sUser);
            SUser temp = sUserDao.queryByPk(sUser);
            //只有正常才能注销
            if (StringUtil.isEmpty(temp.getStatus()) || ConsoleConstant.USER_STATUS_0.equals(temp.getStatus())) {
                logger.debug("注销用户不能修改");
                return -1;
            }
            if (inSUserVo.getOrgCode()!=null&&!("".equals(inSUserVo.getOrgCode()))) {
                sUser.setLegalOrgCode(inSUserVo.getLegalOrgCode());
                SUserOrg sUserOrg = new SUserOrg();
                sUserOrg.setUserCode(inSUserVo.getUserCode());
                sUserOrg.setOrgCode(inSUserVo.getOrgCode());
                sUserOrg.setLegalOrgCode(inSUserVo.getLegalOrgCode());
                sUserOrg.setLastUpdateUser(inSUserVo.getLoginUserId());
                sUserOrg.setLastUpdateTime(TimeUtil.getCurrentDateTime());
                num += sUserOrgDao.updateByPk(sUserOrg);
            }
            num += sUserDao.updateByPk(sUser);
        } catch (Exception e) {
            logger.error("修改数据发生异常!", e);
            num = -1;
        }
        logger.debug("根据条件:" + inSUserVo + "修改的数据条数为" + num);
        return num;
    }

    @Override
    public int pwdByPk(SUserVO inSUserVo) {
        logger.debug("当前修改数据为:" + inSUserVo.toString());
        int num = 0;
        try {
            SUser sUser = new SUser();
            beanCopy(inSUserVo, sUser);
            setUpdateDefaultProperty(sUser);
            SUser temp = sUserDao.queryByPk(sUser);
            //只有正常才能注销
            if (StringUtil.isEmpty(temp.getStatus()) || ConsoleConstant.USER_STATUS_0.equals(temp.getStatus())) {
                logger.debug("注销用户不能修改");
                return -1;
            }
            sUser.setUserPwd(MD5Util.getMD5ofStr(sUser.getUserCode()+sUser.getUserCode()));
            num += sUserDao.pwdByPk(sUser);
        } catch (Exception e) {
            logger.error("修改数据发生异常!", e);
            num = -1;
        }
        logger.debug("根据条件:" + inSUserVo + "修改的数据条数为" + num);
        return num;
    }

    @Override
    public int setUserRole(SUserRoleVO sUserRoleVO) {
        try {
            SUser sUser = new SUser();
            sUser.setUserCode(sUserRoleVO.getUserCode());
            SUser temp = sUserDao.queryByPk(sUser);
            //只有正常才能注销
            if (StringUtil.isEmpty(temp.getStatus()) || ConsoleConstant.USER_STATUS_0.equals(temp.getStatus())) {
                logger.debug("注销用户不能修改");
                return -1;
            }
            List<String> newUserRoleVOS = sUserRoleVO.getRoleCodes();
            //旧的角色码列表
            List<String> oldRoleCodes = sUserRoleDao.queryRoles(sUserRoleVO.getUserCode());
            if (oldRoleCodes.isEmpty() && newUserRoleVOS.isEmpty()) {
                return -1;
            }

            List<String> addRoleCodes = null; //新增的角色码列表
            List<String> deleteRoleCodes = null; //删除的角色码列表
            if (oldRoleCodes.isEmpty()) {
                addRoleCodes = newUserRoleVOS; //如果旧的没有, 则所有新的角色码都是新增的
            } else if (newUserRoleVOS.isEmpty()) {
                deleteRoleCodes = oldRoleCodes; //如果新的没有，则是删除所有旧的
            } else {
//			在原数组没有的，新数组有的， 则是新增的
//			在新数组没有的，老数组有的， 则是删除的
                addRoleCodes = new ArrayList<>();
                deleteRoleCodes = new ArrayList<>();
                int flag;
                for (String newUserRoleVO : newUserRoleVOS) {
                    if (null == newUserRoleVO || "".equals(newUserRoleVO.trim()))
                        break;
                    //新数组的元素在老数组里面查找元素， 如果无，则是新增的
                    flag = 0;
                    for (String oldRoleCode : oldRoleCodes) {
                        if (newUserRoleVO.equals(oldRoleCode)) {
                            flag++;
                            break;
                        }
                    }
                    if (flag == 0)
                        addRoleCodes.add(newUserRoleVO);
                }

                for (String oldRoleCode : oldRoleCodes) {
                    //老数组的元素在新数组里面查找元素， 如果无，则是删除的
                    flag = 0;
                    for (String newUserRoleVO : newUserRoleVOS) {
                        if (null == newUserRoleVO
                                || "".equals(newUserRoleVO.trim()))
                            break;
                        if (oldRoleCode.equals(newUserRoleVO)) {
                            flag++;
                            break;
                        }
                    }
                    if (flag == 0)
                        deleteRoleCodes.add(oldRoleCode);
                }


            }
            int flag = 0;
            SUserRole sUserRole = new SUserRole();
            if (null != deleteRoleCodes && !deleteRoleCodes.isEmpty()) {

                for (String deleteRoleCode : deleteRoleCodes) {
                    sUserRole.setLoginUserId(sUserRoleVO.getLoginUserId());
                    setInsertDefaultProperty(sUserRole);
                    sUserRole.setUserCode(sUserRoleVO.getUserCode());
                    sUserRole.setRoleCode(deleteRoleCode);
                    flag += sUserRoleDao.deleteByPk(sUserRole);
                }
            }
            if (null != addRoleCodes && !addRoleCodes.isEmpty()) {
                for (String addRoleCode : addRoleCodes) {
                    sUserRole.setLoginUserId(sUserRoleVO.getLoginUserId());
                    setInsertDefaultProperty(sUserRole);
                    sUserRole.setUserCode(sUserRoleVO.getUserCode());
                    sUserRole.setRoleCode(addRoleCode);
                    flag += sUserRoleDao.insertSUserRole(sUserRole);
                }
            }
            logger.debug("根据条件:" + sUserRoleVO + "修改的数据条数为" + flag);
            return flag;
        }catch (Exception e){
            logger.debug("设置角色错误");
            return -1;
        }
    }

    @Override
    public int setUserDuty(SUserDutyVO sUserDutyVO) {
        try {
            SUser sUser = new SUser();
            sUser.setUserCode(sUserDutyVO.getUserCode());
            SUser temp = sUserDao.queryByPk(sUser);
            //只有正常才能注销
            if (StringUtil.isEmpty(temp.getStatus()) || ConsoleConstant.USER_STATUS_0.equals(temp.getStatus())) {
                logger.debug("注销用户不能修改");
                return -1;
            }
        List<String> newDutyRoleVOS = sUserDutyVO.getDutyCodes();
            //旧的岗位码列表
            List<String> oldRoleCodes = sUserDutyDao.queryDuty(sUserDutyVO.getUserCode());
            if (oldRoleCodes.isEmpty() && newDutyRoleVOS.isEmpty()) {
                return -1;
            }
            List<String> addRoleCodes = null; //新增的岗位码列表
            List<String> deleteRoleCodes = null; //删除的岗位码列表
            if (oldRoleCodes.isEmpty()) {
                addRoleCodes = newDutyRoleVOS; //如果旧的没有, 则所有新的岗位码都是新增的
            } else if (newDutyRoleVOS.isEmpty()) {
                deleteRoleCodes = oldRoleCodes; //如果新的没有，则是删除所有旧的
            } else {
//			在原数组没有的，新数组有的， 则是新增的
//			在新数组没有的，老数组有的， 则是删除的
                addRoleCodes = new ArrayList<>();
                deleteRoleCodes = new ArrayList<>();
                int flag;
                for (String newDutyRoleVO : newDutyRoleVOS) {
                    if (null == newDutyRoleVO || "".equals(newDutyRoleVO.trim()))
                        break;
                    //新数组的元素在老数组里面查找元素， 如果无，则是新增的
                    flag = 0;
                    for (String oldRoleCode : oldRoleCodes) {
                        if (newDutyRoleVO.equals(oldRoleCode)) {
                            flag++;
                            break;
                        }
                    }
                    if (flag == 0)
                        addRoleCodes.add(newDutyRoleVO);
                }

                for (String oldRoleCode : oldRoleCodes) {
                    //老数组的元素在新数组里面查找元素， 如果无，则是删除的
                    flag = 0;
                    for (String newDutyRoleVO : newDutyRoleVOS) {
                        if (null == newDutyRoleVO
                                || "".equals(newDutyRoleVO.trim()))
                            break;
                        if (oldRoleCode.equals(newDutyRoleVO)) {
                            flag++;
                            break;
                        }
                    }
                    if (flag == 0)
                        deleteRoleCodes.add(oldRoleCode);
                }


            }
            int flag = 0;
            SUserDuty sUserDuty = new SUserDuty();

            if (null != deleteRoleCodes && !deleteRoleCodes.isEmpty()) {

                for (String deleteRoleCode : deleteRoleCodes) {
                    sUserDuty.setLoginUserId(sUserDutyVO.getLoginUserId());
                    setInsertDefaultProperty(sUserDuty);
                    sUserDuty.setUserCode(sUserDutyVO.getUserCode());
                    sUserDuty.setDutyCode(deleteRoleCode);
                    flag += sUserDutyDao.deleteByPk(sUserDuty);
                }
            }
            if (null != addRoleCodes && !addRoleCodes.isEmpty()) {
                for (String addRoleCode : addRoleCodes) {
                    sUserDuty.setLoginUserId(sUserDutyVO.getLoginUserId());
                    setInsertDefaultProperty(sUserDuty);
                    sUserDuty.setUserCode(sUserDutyVO.getUserCode());
                    sUserDuty.setDutyCode(addRoleCode);
                    flag += sUserDutyDao.insertSUserDuty(sUserDuty);
                }
            }
            logger.debug("根据条件:" + sUserDutyVO + "修改的数据条数为" + flag);
            return flag;
        }catch (Exception e){
            logger.debug("设置角色错误");
            return -1;
        }
    }


    /**
     * 查询操作
     */
    public SUserVO queryByPk(SUserVO inSUserVo) {

        logger.debug("当前查询参数信息为:" + inSUserVo);
        try {
            SUser querySUser = new SUser();
            beanCopy(inSUserVo, querySUser);
            SUser queryRslSUser = sUserDao.queryByPk(querySUser);
            if (Objects.nonNull(queryRslSUser)) {
                SUserVO sUserVO = beanCopy(queryRslSUser, new SUserVO());
                logger.debug("当前查询结果为:"+ sUserVO.toString());
                return sUserVO;
            } else {
                logger.debug("当前查询结果为空!");
            }
        } catch (Exception e) {
            logger.error("查询数据发生异常!", e);
        }
        return null;
    }


    /**
     * 查询用户权限数据
     */
    @SuppressWarnings("unchecked")
    public List<SUserVO> queryColtUserByPage(SUserVO sUserVo) {

        logger.debug("当前查询本人所属数据信息的参数信息为:");
        List<SUserVO> list = null;
        try {
            List<SUserVO> sUsers = sUserDao.queryColtUserByPage(sUserVo);
            logger.debug("当前查询本人所属数据信息的结果集数量为:" + sUsers.size());
            pageSet(sUsers, sUserVo);
            list = (List<SUserVO>) beansCopy(sUsers, SUserVO.class);
        } catch (Exception e) {
            logger.error("数据转换出现异常!", e);
        }

        return list;

    }
     
    /**
     * 查询用户权限数据(调单查询)
     */
    @SuppressWarnings("unchecked")
    public List<SUserVO> queryAdjustColtUser(SUserVO sUserVo) {

        logger.debug("当前查询本人所属数据信息的参数信息为:");
        List<SUserVO> list = null;
        try {
            List<SUserVO> sUsers = sUserDao.queryAdjustColtUserByPage(sUserVo);
            logger.debug("当前查询本人所属数据信息的结果集数量为:" + sUsers.size());
            pageSet(sUsers, sUserVo);
            list = (List<SUserVO>) beansCopy(sUsers, SUserVO.class);
        } catch (Exception e) {
            logger.error("数据转换出现异常!", e);
        }

        return list;

    }

    @SuppressWarnings("unchecked")
     public List<SUserVO> queryAllOwner(SUserVO sUserVo) {

         logger.debug("当前查询本人所属数据信息的参数信息为:");
         List<SUserVO> list = null;
         try {
             List<SUserVO> sUsers = sUserDao.queryAllOwnerByPage(sUserVo);
             logger.debug("当前查询本人所属数据信息的结果集数量为:" + sUsers.size());
             pageSet(sUsers, sUserVo);
             list = (List<SUserVO>) beansCopy(sUsers, SUserVO.class);
         } catch (Exception e) {
             logger.error("数据转换出现异常!", e);
         }

         return list;

     }
     
    @SuppressWarnings("unchecked")
    @Override
    public List<SUserVO> queryAllOrgByPage(SUserVO sUserVo) {
        logger.debug("当前查询本人所属数据信息的参数信息为:");
        List<SUserVO> list = null;
        try {
            List<SUserVO> sUsers = sUserDao.queryAllOrgByPage(sUserVo);
            logger.debug("当前查询本人所属数据信息的结果集数量为:" + sUsers.size());
            pageSet(sUsers, sUserVo);
            list = (List<SUserVO>) beansCopy(sUsers, SUserVO.class);
        } catch (Exception e) {
            logger.error("数据转换出现异常!", e);
        }

        return list;
    }


    /**
     * 查询当前机构权限数据
     */
    @SuppressWarnings("unchecked")
    public List<SUserVO> queryAllCurrOrg(SUserVO sUserVo) {

        logger.debug("当前查询本人所属机构数据信息的参数信息为:");
        List<SUserVO> sUsers = sUserDao.queryAllCurrOrgByPage(sUserVo);
        logger.debug("当前查询本人所属机构数据信息的结果集数量为:" + sUsers.size());
        List<SUserVO> list = null;
        try {
            pageSet(sUsers, sUserVo);
            list = (List<SUserVO>) beansCopy(sUsers, SUserVO.class);
        } catch (Exception e) {
            logger.error("数据转换出现异常!", e);
        }

        return list;

    }


    /**
     * 查询当前机构及下属机构权限数据
     */
    @SuppressWarnings("unchecked")
    public List<SUserVO> queryAllCurrDownOrg(SUserVO sUserVo) {

        logger.debug("当前查询本人所属机构及以下数据信息的参数信息为:");
        List<SUserVO> sUsers = sUserDao.queryAllCurrDownOrgByPage(sUserVo);
        logger.debug("当前查询本人所属机构及以下数据信息的结果集数量为:" + sUsers.size());
        List<SUserVO> list = null;
        try {
            pageSet(sUsers, sUserVo);
            list = (List<SUserVO>) beansCopy(sUsers, SUserVO.class);
        } catch (Exception e) {
            logger.error("数据转换出现异常!", e);
        }

        return list;

    }

    /**
     * 查询当前机构及下属机构权限数据
     */
    public List<SUserVO> queryAllUserByLegalOrg(SUserVO sUserVo) {

        logger.debug("当前查询法人机构下的用户参数信息为:");
        List<SUserVO> sUsers = sUserDao.queryAllUserByLegalOrg(sUserVo);
        logger.debug("当前查询法人机构下的用户结果集数量为:" + sUsers.size());
        return sUsers;

    }

	@SuppressWarnings("unchecked")
	@Override
	public List<SUserVO> queryUsersByCondition(SUserVO sUserVo) {

        logger.debug("查询条件的参数信息为:" + sUserVo.toString());
        List<SUserVO> sUsers = sUserDao.queryUsersByConditionByPage(sUserVo);
        logger.debug("查询条件的结果集数量为:" + sUsers.size());
        List<SUserVO> list = null;
        try {
            pageSet(sUsers, sUserVo);
            list = (List<SUserVO>) beansCopy(sUsers, SUserVO.class);
        } catch (Exception e) {
            logger.error("数据转换出现异常!", e);
        }

        return list;
    }

    @Override
    public List<SUserVO> queryUsersByOrgCode(String code) {
        logger.debug("查询条件的参数信息为:" + code);
        return sUserDao.queryUsersByOrgCode(code);
    }

    @Override
    public List<SUserVO> queryUSByOrgCode(String code) {
        logger.debug("查询条件的参数信息为:" + code);
        return sUserDao.queryUSByOrgCode(code);
    }

    @Override
    public String queryUserNameByUserId(String userId){
        logger.debug("当前数据条件为:"+ userId);
        String userName = "";
        try {
            userName = sUserDao.queryUserNameByUserId(userId);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询用户数据发生异常!", e);
        }
        return userName;
    }

}
